<?php
/**
 * 事件
 * 
 * @author ShuangYa
 * @package EasyAccount
 * @category Library
 * @link https://www.sylingd.com/
 * @copyright Copyright (c) 2018 ShuangYa
 * @license https://www.sylibs.com/go/apigateway/license
 */
namespace ea\library;

use yesf\Yesf;
use yesf\library\Plugin;
use ea\model\Config;

class PluginHandler {
	private static function checkAdmin($token, $tverify) {
		if (empty($token) || empty($tverify) || ($v = Token::verify($token, $tverify)) === FALSE) {
			return FALSE;
		} else {
			$user = User::get($v['uid']);
			if ($user['role'] != 2 && $user['role'] != 1) {
				return FALSE;
			}
			return $user;
		}
	}
	/**
	 * HTTP分发
	 * 
	 * @access public
	 * @param string $module
	 * @param string $controller
	 * @param string $action
	 * @param object $request
	 * @param object $response
	 */
	public static function onBeforeDispatcher($module, $controller, $action, $request, $response) {
		if ($request->server['request_method'] === 'OPTIONS') {
			$response->header('Access-Control-Allow-Origin', $request->header['origin']);
			$response->header('Access-Control-Allow-Credentials', 'true');
			return TRUE;
		}
		if ($module === 'admin') {
			$super_admin = $request->headers['x-admin-password'];
			if ($super_admin !== Config::getInstance()->read('admin_password')) {
				$super_admin = NULL;
			}
			if (!$super_admin) {
				$token = $request->cookie[Utils::getCookieName('token')];
				$tverify = $request->cookie[Utils::getCookieName('tverify')];
				$request->user = self::checkAdmin($token, $tverify);
			} else {
				$request->user = 'super';
			}
			if ($controller !== 'index') {
				$response->header('Content-Type', 'application/json; charset=UTF-8');
				if (!$request->user) {
					$response->write(Utils::getWebApiResult([
						'error' => '未登录'
					]));
					return TRUE;
				}
			}
		}
		return NULL;
	}
	public static function onRouterStart($uri) {
		if (strpos($uri, 'oauthclient/callback/') === 0) {
			return [[
				'type' => substr($uri, 15)
			], [
				'module' => 'index',
				'controller' => 'oauthclient',
				'action' => 'callback'
			]];
		}
		return NULL;
	}
	public static function onWorkerStart($worker_id, $is_task) {
		Yesf::setBaseUri(Yesf::app()->getConfig('urlPrefix'));
	}
}